import axios from 'axios'
import router from '../router'
import iView from 'iview'
import {
  getToken
} from './_tokenHelper'

function handleError (error) {
  // Quasar Toast Schema
  let message = ''
  if (typeof error.response !== 'undefined') {
    if (error.response.status === 403) {
      router.push('/login')
    }
    // Setup Generic Response Messages
    if (error.response.status === 401) {
      message = 'UnAuthorized'
    } else if (error.response.status === 404) {
      message = 'url 不存在'
    } else if (error.response.status === 405) {
      message = 'API Route Method Not Allowed'
    } else if (error.response.status === 422) {
      // Validation MessageRequest failed
    } else if (error.response.status >= 500) {
      let type = error.response.data.type
      if (type == 'application/json') {
        let msg
        let reader = new FileReader()
        reader.readAsText(error.response.data)
        reader.onload = function () {
          let content = reader.result
          msg = JSON.parse(content).message
          setTimeout(() => {
            message = msg
            iView.Message.error(msg)
          }, 500)
        }
      } else if (error.response.data) {
        let blob = new Blob([error.response.data])
        let msg
        let reader = new FileReader()
        reader.readAsText(blob, 'utf-8')
        reader.onload = function () {
          let content = reader.result
          msg = JSON.parse(content).message
          setTimeout(() => {
            message = msg
            iView.Message.error(msg)
          }, 500)
        }
      }
      message = 'Server Error'
    }
    // Try to Use the Response Message
    if (error.hasOwnProperty('response') && error.response.hasOwnProperty('data')) {
      if (error.response.data.hasOwnProperty('message') && error.response.data.message.length > 0) {
        message = '系统错误  ' + error.response.data.message
      }
    }
  }
  // Toast the Message
  if (message.length > 0) {
    iView.Message.error(message)
  }
}

axios.interceptors.request.use((request) => {
  request.headers.Token = getToken()
  iView.Spin.show({
    render: (h) => {
      return h('div', [
        h('Icon', {
          'class': 'demo-spin-icon-load',
          props: {
            type: 'ios-loading',
            size: 20
          }
        }),
        h('div', '正在加载')
      ])
    }
  })
  return request
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

axios.interceptors.response.use((response) => {
  iView.Spin.hide()
  if (response.data.status) {
    let msg = response.data.msg
    if (response.data.status === 301) {
      iView.Message.info('登录已失效，重新登录')
      router.push('/login')
    } else if (response.data.status != 200) {
      iView.Message.error({
        content: msg,
        duration: 2
      })
    } else if (response.data.status == 200) {
      let newMsg = ''
      if (msg == null) {
        newMsg = '成功'
      } else {
        newMsg = msg
      }
      iView.Message.success({
        content: newMsg,
        duration: 1
      })
    }
  }
  return response
}, (error) => {
  iView.Spin.hide()
  handleError(error)
  return Promise.reject(error)
})
